package com.ellecity06.cwhiskymall.ui.webview

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ClipData
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.annotation.Nullable
import androidx.core.content.FileProvider
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.engine.PictureSelectorGlideEngine
import com.ellecity06.common.engine.PictureSelectorSandboxFileEngine
import com.ellecity06.common.ktx.hasReadImagePermission
import com.ellecity06.common.ktx.hasReadVideoPermission
import com.ellecity06.common.ktx.statusBar
import com.ellecity06.common.ktx.upPath
import com.ellecity06.common.utils.CommonUtils
import com.ellecity06.common.utils.CommonUtils.Companion.isInstallAPIK
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.common.widgets.dialog.showAlert
import com.ellecity06.cwhiskymall.databinding.ActivityWebBinding
import com.ellecity06.cwhiskymall.storage.AppStorage
import com.ellecity06.cwhiskymall.utils.LogUtils
import com.gyf.immersionbar.ktx.statusBarHeight
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.style.PictureSelectorStyle
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.*
import java.io.File

/**
 * @author ellecity06
 * @time 2024/10/22 16:21
 * @des 用于打开webH5页面
 */
class WebActivity : BaseMvvmActivity<ActivityWebBinding, WebViewModel>() {
    private val url: String by lazy { intent.getStringExtra(URL) ?: "" }
    private val title: String? by lazy { intent.getStringExtra(TITLE) }
    private val content: String? by lazy { intent.getStringExtra(CONTENT) }
    private val sign: Boolean by lazy { intent.getBooleanExtra("isSign", false) }

    /**
     * token 类型 0-商城token ,1-数据流转的token
     */
    private val tokenType: Int by lazy { intent.getIntExtra(TOKEN_TYPE, 0) }
    private val needToken: Boolean by lazy { intent.getBooleanExtra(NEED_TOKEN, true) }
    var valueCallback: ValueCallback<Array<Uri?>?>? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AndroidBug5497Workaround.assistActivity(this)
    }

    override fun inflateBinding(): ActivityWebBinding {
        return ActivityWebBinding.inflate(layoutInflater)
    }

    override val userBaseTitle: Boolean
        get() = false

    override fun initialize(savedInstanceState: Bundle?) {
        statusBar(binding.statusBar)
        if (title.isNullOrEmpty()) {
            hideTitle()
        } else {
            showTitle(title ?: "")
        }
        binding.ivBack.setOnClickListener { onBackPressed() }
        binding.ivClose.setOnClickListener { finish() }
        initWebView()

    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        binding.webView.requestFocusFromTouch()
        val settings: WebSettings = binding.webView.settings
        settings.javaScriptEnabled = true
        settings.displayZoomControls = false
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.allowFileAccess = true
        settings.domStorageEnabled = true
        settings.setAppCacheEnabled(false)
        settings.builtInZoomControls = false
        binding.webView.addJavascriptInterface(CommonWebScript(this), "android")

        binding.webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(v: WebView?, url: String?): Boolean {

logD("shouldOverrideUrlLoading=$url")
                if (url!!.startsWith("alipays:")) {
                    if (!isInstallAPIK(applicationContext, "com.eg.android.AlipayGphone")) {
                        ToastUtils.show("没有安装支付宝")
                        return false
                    } else {
                        LogUtils.e("plurality:" + url)
                        startActivity(Intent("android.intent.action.VIEW", Uri.parse(url)));
                    }
                    return true
                    //
                } else if (url.startsWith("weixin://wap/pay?") || url.startsWith("weixin://dl/business/")) {
                    if (!CommonUtils.checkWeChatInstalled(this@WebActivity)) {
                        ToastUtils.show("没有安装微信")
                        return false
                    } else {
                        try {
                            startActivity(Intent("android.intent.action.VIEW", Uri.parse(url)));

                        } catch (e: Exception) {
                            Log.e("test", "weixin未安装")
                        }
                    }
                    return true
                } else {

                    if (url.startsWith("http:") || url.startsWith("https:")) {
//                        val lStringStringHashMap: HashMap<String, String> = HashMap()
//
//                        lStringStringHashMap["referer"] = "http://h5.yysh888.com"
//                        v!!.loadUrl(url, lStringStringHashMap)
                    } else {


                        if (CommonUtils.isLink(url)) {
                            binding.webView.loadUrl(url)
                            return true
                        }
                        return super.shouldOverrideUrlLoading(v, url)
                    }
                    return super.shouldOverrideUrlLoading(v, url)
                }
            }


            override fun onReceivedSslError(
                p0: WebView?,
                p1: SslErrorHandler?,
                p2: com.tencent.smtt.export.external.interfaces.SslError?
            ) {
                //super.onReceivedSslError(p0, p1, p2)
                p1?.proceed()

            }

        }
        binding.webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(v: WebView?, newProgress: Int) {
//                if (newProgress >= 100) {
//                    binding.pbH5.visibility = View.GONE
//                    binding.webView.evaluateJavascript("javascript:setToken('${AppStorage.token}')") {
//                        //这里返回JS的结果
//                        LogUtils.e("js的回调 $it")
//                    }
//                }
                super.onProgressChanged(v, newProgress)
            }

            override fun onReceivedTitle(view: WebView?, h5Title: String?) {
                /*if (binding.tvTitle.text.isEmpty()) {
                    binding.tvTitle.text =title
                }*/
                logD("h5Title=$h5Title")
                if (title != null && title!!.isNotEmpty() && h5Title != null) {
                    binding.tvTitle.text = h5Title
                }
            }

            // Android > 5.0 调用这个方法
            override fun onShowFileChooser(
                webView: WebView?,
                filePathCallback: ValueCallback<Array<Uri?>?>?,
                fileChooserParams: FileChooserParams?
            ): Boolean {
                if (filePathCallback != null) {
                    valueCallback = filePathCallback
                }
                var type = "image/*"
                if (fileChooserParams?.acceptTypes != null && fileChooserParams.acceptTypes.isNotEmpty()) {
                    type = fileChooserParams.acceptTypes[0]
                }
                if (type.contains("video")) {
                    if (hasReadVideoPermission()) {
                        selectImage(SelectMimeType.ofVideo())

                    } else {
                        showAlert(content = "获取视频需要存储权限，当您需要拍摄视频时会需要您的相机权限录制视频") {
                            selectImage(SelectMimeType.ofVideo())
                        }
                    }
                } else {
                    if (hasReadImagePermission()) {
                        selectImage(SelectMimeType.ofImage())
                    } else {
                        showAlert(content = "获取相片需要您的存储权限，当您需要拍照是会需要您的相机权限拍摄相片") {
                            selectImage(SelectMimeType.ofImage())
                        }

                    }
                }

                return true
            }
        }
        // 加载Html标签
        if (!content.isNullOrEmpty() && url.isEmpty()) {
            binding.webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null)
        } else {
            var h5Url = url
            if (needToken) {
                val token = if (tokenType == 1) AppStorage.assetsToken ?: "" else AppStorage.token ?: ""
                h5Url += String.format(
                    if (url.contains("?")) "&%s" else "?%s",
                    "token=${token}&statusBarHeight=${statusBarHeight}&fromsource=App_Android&source=jiudage"
                )
            }
            // ipH5需要带这个
            if (tokenType==1){
                h5Url+= "&type=shopToLoginCae"
            }
            logD("h5=$h5Url")
            binding.webView.loadUrl(h5Url)

        }
    }

    private fun selectImage(type: Int) {
        PictureSelector.create(this)
            .openGallery(type)
            .setSandboxFileEngine(PictureSelectorSandboxFileEngine())
            .setMaxSelectNum(1)
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(PictureSelectorGlideEngine.createGlideEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    if (valueCallback != null && result != null)
                        valueCallback?.onReceiveValue(uploadFiles(result))
                }

                override fun onCancel() {
                    valueCallback?.onReceiveValue(null)
                    valueCallback = null
                }
            })
    }

    fun uploadFiles(result: MutableList<LocalMedia?>?): Array<Uri?>? {
        if (result.isNullOrEmpty()) {
            return null
        }
        val array: Array<Uri?> = Array(result.size) {
            try {
                FileProvider.getUriForFile(
                    this,
                    "$packageName.fileProvider",
                    File(result[it]!!.upPath())
                )

            } catch (e: Exception) {
                Uri.fromFile(File(result[it]!!.realPath))
            }
        }
        return array
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        @Nullable data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    selectH5File(data, valueCallback)
                }
            } else {
                //取消选择
                if (valueCallback != null) {
                    valueCallback!!.onReceiveValue(null)
                }
            }
        } else if (resultCode == REQUEST_ALIPAY_CODE) {

        }
    }

    private fun selectH5File(
        data: Intent,
        valueCallback: ValueCallback<Array<Uri?>?>?
    ) {
        var valueCallback: ValueCallback<Array<Uri?>?>? = valueCallback ?: return
        try {
            var results: Array<Uri?>?
            val dataString = data.dataString
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                val clipData: ClipData? = data.clipData
                if (clipData != null) {
                    results = arrayOfNulls(clipData.itemCount)
                    for (i in 0 until clipData.itemCount) {
                        val item: ClipData.Item = clipData.getItemAt(i)
                        results[i] = item.uri
                    }
                }
            }
            if (dataString != null) {
                results = arrayOf(Uri.parse(dataString))
                valueCallback?.onReceiveValue(results)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        valueCallback = null
    }


    companion object {
        private const val TITLE: String = "key_title"
        private const val URL: String = "key_url"
        private const val CONTENT: String = "key_content"
        private const val SIGN: String = "key_sign"
        private const val TOKEN_TYPE: String = "key_token_type"

        private const val NEED_TOKEN: String = "KEY_NEED_TOKEN"
        private val REQUEST_CODE = 142
        val REQUEST_ALIPAY_CODE = 143

        /**
         * 开启webView页面 title为空则表示不需要自带导航栏
         * @param tokenType token类型 0-商城token 1-应用流转平台的token 默认是商城的
         */
        @JvmStatic
        @JvmOverloads
        fun launch(
            activity: Activity,
            url: String,
            title: String? = null,
            content: String? = null,
            sign: Boolean = false,
            needToken: Boolean = true,
            tokenType: Int = 0
        ) {
            activity.startActivity(Intent(activity, WebActivity::class.java).apply {
                putExtra(URL, url)
                putExtra(TITLE, title)
                putExtra(CONTENT, content)
                putExtra(SIGN, sign)
                putExtra(NEED_TOKEN, needToken)
                putExtra(TOKEN_TYPE, tokenType)

            })
        }
    }

    override fun onBackPressed() {
        if (binding.webView.canGoBack()) {
            binding.webView.goBack()
        } else {
            super.onBackPressed()
        }
    }

    fun showTitle(title: String) {
        binding.tvTitle.text = title
        binding.statusBar.visibility = View.VISIBLE
        binding.layoutTitle.visibility = View.VISIBLE
    }

    fun hideTitle() {
        binding.statusBar.visibility = View.GONE
        binding.layoutTitle.visibility = View.GONE
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.webView.stopLoading()
        binding.webView.removeAllViews()
        binding.webView.clearCache(true)
        binding.webView.clearHistory()
        binding.webView.destroy()
    }
}